<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Rand extends CI_Controller {

	public function __construct()
	    {
	        parent :: __construct(); 
	        // Here you should add some sort of user validation
	        // to prevent strangers from pulling your table data
	    } 
	public function img(){
		
		$this->load->library('image_lib');
		$config['image_library'] = 'gd2';
		$config['dynamic_output'] = true;
		$config['source_image'] = 'application/img/hbg_03.png';
		$config['wm_text'] = '段';
		$config['quality'] = '100';
		$config['wm_type'] = 'text';
		$config['wm_font_path'] = 'application/img/simkai.ttf';
		$config['wm_font_size'] = '16';
		$config['wm_font_color'] = '000';
		$config['wm_vrt_alignment'] = 'bottom';
		$config['wm_hor_alignment'] = 'center';
		$config['wm_padding'] = '0';
		
		
		$this->image_lib->initialize($config); 

		//$html = "<img src=".$this->image_lib->watermark()."  />";
		
		$this->image_lib->watermark();
		



		//echo $html ;
	}
	public function index($message=""){
		$this->data['error'] = $message;
		$this->load->view('random/home.html',$this->data);
	}

	public function query($message=""){
		$this->data['error'] = $message;
		$this->load->view('random/query.html',$this->data);
	}

	public function randomCode($numbers){//不重复的1到50000的数组下标
		$randomCode = rand(1,50000);
		if(isset($numbers[$randomCode]) ){
				return	$this->randomCode($numbers);
			}else{
				return $randomCode;
			}

	}


	public function clearCookie(){
		setcookie("useTime","",time()-1);
	}

	public function getNewNum()
	{

		 
		if(  !empty($_COOKIE['useTime'])  ){
			$user_cookie = $_COOKIE['useTime'];

			if($user_cookie >= 5){

				$message = '您的操作太频繁，请稍后再尝试！';
				return $this->index($message);
				// var_dump($user_cookie);
				// exit();

			}else{

				$user_cookie += 1;
				setcookie('useTime',$user_cookie,time()+200);
			}
			
		}else{
			$user_cookie = 1;
			setcookie('useTime',$user_cookie,time()+200);
		}

		// var_dump($_COOKIE['useTime']);
		// exit();
		
		$userInputNum = $this->input->post('number');
		$userInputNum = str_replace(" ","",$userInputNum);
		
		if((preg_match("/^\d*$/",$userInputNum))&&$userInputNum != ""){
			//return;
		}else{
			$message = '请输入数字';
			return $this->index($message);
			
		}

		if($userInputNum>10000){
			$message = '您输入的数字过大！';
			return $this->index($message);
		}else{						
		}

		if($userInputNum <= 0){
			$message = '您输入的数字太小！';
			return $this->index($message);
		}else{
						
		}

		$userIp = $this->getIP();
		$time = time();
		//$this->checkUserCondition($userIp);//检查用户的操作情况
		
		// if(strlen($userIp)>4){//说明ip已经获取到
		// 	if($this->checkUserCondition($userIp)){

		// 	}else{
		// 		$message = '您的操作太频繁，请稍后再尝试！';
		// 		return $this->index($message);
		// 	}
		// }
		
		
		$this->load->model('random_tool_model');		
		$randomSeed = $this->randomCipher();//不重复随机8位种子
		$numbers  = array();
		$newNumbers = array();
		for( $i=1; $i<=$userInputNum; $i++ ){

			$randomCode = $this->randomCode($numbers);

			
			$numbers[$randomCode] = $i;
			
			
		}

		ksort($numbers);

		foreach ($numbers as $key => $value) {
			array_push($newNumbers,$value);
		}


		$jsonNumbers = json_encode($newNumbers);

		$userIp = 'inet_aton("'.$userIp.'")';
			//$userIp = "inet_aton('"	.$userIp."')";		
	    $query = "insert into medicine_kit_random_tool (content,code,digits,ip,inserttime) 
	    values ('".$jsonNumbers."','".$randomSeed."','".$userInputNum."',".$userIp.",'".$time."') ";

		// $this->random_tool_model->insert(array('content' => $jsonNumbers, 'code' => $randomSeed,
		//  'digits'=>$userInputNum,'ip'=>$userIp,'inserttime' =>$time));
	   
		$this->random_tool_model->doInsert($query);


		$this->data['type'] = 'index';
		$this->data['code'] = $randomSeed;
		$this->data['number'] = $newNumbers;
		$this->load->view('random/content.html',$this->data);
	}

	public function getNumWithCode(){
		$code = $this->input->post('code');

		$code = str_replace(" ","",$code);

		if((preg_match("/^\d*$/",$code))&&$code != ""){

		}else{
			$message = '请输正确的随机数种子！';
			return $this->query($message);
		}

		$this->load->model('random_tool_model');
		$numbers = $this->random_tool_model->selectCode(array('code' => $code),'content');
		
		if($numbers){

		}else{
  
			$message = '没有查询到相关数据，请确认随机数种子是否正确！';
			return $this->query($message);
		}

		$newNumbers = json_decode($numbers['content'],true);

		$this->data['type'] = 'query';
		$this->data['code'] = $code;
		$this->data['number'] = $newNumbers;
		$this->load->view('random/content.html',$this->data);
	}

	private function indexError($value){

		if(is_numeric($value)){
			//return;
		}else{
			$message = '请输入数字';
			return $this->index($message);
			
		}
		
	}

	public function checkUserCondition($userIp=""){
		$time = time();
		var_dump($userIp);
		exit();
		$limitTime = 5*60;//用户生成5次随机数后，要5分钟后才能重新生成
		$this->load->model('random_tool_model');
		//$userIp = 'inet_ntoa("'.$userIp.'")';
		$query = "select inserttime from medicine_kit_random_tool where inet_ntoa(ip) = '".$userIp."' order by inserttime desc limit 0,5";
		
		$numbers = $this->random_tool_model->doQuery($query);

		if(count($numbers) >= 5){
			$lastFiveTime = $numbers[0]['inserttime'];
			

			$pastTime = (int)$time - (int)$lastFiveTime;


			if($pastTime < $limitTime){
				
				return false;

			}else{
				return true;
			}
		}else{
			return true;
		}
		

	}

	public function test(){
		$this->load->view('random/content.html');
	}

	public function randomCipher($length = 8){//随机8位种子
		$chars = '0123456789';		
        $password = '';
        for ( $i = 0; $i < $length; $i++ ) 
        {
            // 这里提供两种字符获取方式
            // 第一种是使用 substr 截取$chars中的任意一位字符；
            // 第二种是取字符数组 $chars 的任意元素
            $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
            //$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];
        }

         return $this->okRandomCipher($password);//检查随机种子是否重复
	}

	public function okRandomCipher($code){//检查随机种子是否重复
		$this->load->model('random_tool_model');		
		$isRepCode =  $this->random_tool_model->selectCode(array('code' => $code),'id');
		if($isRepCode){
			return $this->randomCipher();
			
		}else{
			return $code;
			
		}
	}



	public function getExcelWithCode(){

		$code = $this->input->get('code');
		$code = str_replace(" ","",$code);

		$this->load->model('random_tool_model');
		$numbers = $this->random_tool_model->selectCode(array('code' => $code),'content');
		// var_dump($numbers['content']);
		// exit();		
		
		$newNumbers = json_decode($numbers['content'],true);
		
		$this->load->library('PHPExcel');
		// $this->load->library('PHPExcel/Reader/Excel5');
		$this->load->library('PHPExcel/IOFactory');
		$objPHPExcel = new PHPExcel();
		$objPHPExcel->getProperties()->setTitle("export")->setDescription("none");	
		$objPHPExcel->getDefaultStyle()->getFont()->setSize(14);	
		$col = 0;
		$row = 1;
		foreach ($newNumbers as $field)
		{
			
			$objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $field);
			
			$col++;

			if($col%10 ==0){

				$row ++;
				$col = 0;
			}
						
		}

		$objPHPExcel -> setActiveSheetIndex(0);
		$objWriter = IOFactory :: createWriter($objPHPExcel, 'Excel5'); 
        // Sending headers to force the user to download the file
        header('Content-Type: application/vnd.ms-excel');
       	header('Content-Disposition: attachment;filename="随机数' . $code . '.xls"');
        //header('Content-Disposition: attachment;filename="s' . $code . '.xls"');
        header('Cache-Control: max-age=0');
 		
        $objWriter -> save('php://output');


	}

	private function getIP(){

        //$ip = "222.163.253.25";
        $ip = "";
        if (getenv("HTTP_CLIENT_IP"))
        $ip = getenv("HTTP_CLIENT_IP");
        else if(getenv("HTTP_X_FORWARDED_FOR"))
        $ip = getenv("HTTP_X_FORWARDED_FOR");
        else if(getenv("REMOTE_ADDR"))
        $ip = getenv("REMOTE_ADDR");
        else $ip = "";
        return $ip;
       
    }

}